<?php
//公共模型
class CommonAction extends Action {
	protected $sortBy = ''; //单独定义排序字段
	public static $map; //模板里可直接调用，Sys类的查询条件
	public static $id; //模板里可直接调用id值
		
	function _initialize() {
		if(MODULE_NAME=='Ui' && ACTION_NAME=='menu') return; //左侧菜单
		// 用户权限检查
		if (C ( 'USER_AUTH_ON' ) && !in_array(MODULE_NAME,explode(',',C('NOT_AUTH_MODULE')))) {
			import ( 'ORG.Util.RBAC' );
			if (! RBAC::AccessDecision ()) {
				$url = PHP_FILE . C ( 'USER_AUTH_GATEWAY' );
				$url .= isset($_GET['returnUrl']) ? '?returnUrl='.$_GET['returnUrl'] : '';
				//检查认证识别号
				if (! $_SESSION [C ( 'USER_AUTH_KEY' )]) {
					//跳转到认证网关
					redirect ( $url );
				}
				// 没有权限 抛出错误
				if (C ( 'RBAC_ERROR_PAGE' )) {
					// 定义权限错误页面
					redirect ( C ( 'RBAC_ERROR_PAGE' ) );
				} else {
					if (C ( 'GUEST_AUTH_ON' )) {
						$this->assign ( 'jumpUrl', $url );
					}
					// 提示错误信息
					$this->error ( L ( '_VALID_ACCESS_' ) );
				}
			}
		}
	}
	
	public function index() {
		//列表过滤器，生成查询Map对象
		$map = $this->_search ();		
		if (method_exists ( $this, '_filter' )) {
			$this->_filter ( $map );
		}
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$this->_list ( $model, $map, $this->sortBy );
		}		
		$this->display ();
		return;
	}
	/**
     +----------------------------------------------------------
	 * 取得操作成功后要返回的URL地址
	 * 默认返回当前模型的默认操作
	 * 可以在action控制器中重载
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	function getReturnUrl() {
		return __URL__ . '?' . C ( 'VAR_MODULE' ) . '=' . MODULE_NAME . '&' . C ( 'VAR_ACTION' ) . '=' . C ( 'DEFAULT_ACTION' );
	}

	/**
     +----------------------------------------------------------
	 * 根据表单生成查询条件
	 * 进行列表过滤
     +----------------------------------------------------------
	 * @access protected
     +----------------------------------------------------------
	 * @param string $name 数据对象名称
     +----------------------------------------------------------
	 * @return HashMap
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	protected function _search($name = '') {
		//生成查询条件 “常州  车讯”这样的条件，必须构造成'title&title'=>array('常州','车讯','_multi'=>true),即可。
		/*		
		$map = array(
			'title&title'=>array('常州','车讯','_multi'=>true),
			'module'=>'Article',
			);
		*/	
		if (empty ( $name )) {
			$name = $this->getActionName();
		}
		$name=$this->getActionName();
		$model = D ( $name );
		$fields = $model->getDbFields ();
		unsetValue($fields, 'tid');
		$map = getSearchMap($fields);
		$map = array_merge(D('Common')->getCategoryMap($_REQUEST['tid']), $map);	
		if(isset($_REQUEST['keytype'])){
			$where = getSearchMap(array($_REQUEST['keytype']=>'keyword'));
			if($where) $map['_complex'] = $where;
		}
		//dump($map);
		return $map;
	}

	/**
     +----------------------------------------------------------
	 * 根据表单生成查询条件
	 * 进行列表过滤
     +----------------------------------------------------------
	 * @access protected
     +----------------------------------------------------------
	 * @param Model $model 数据对象
	 * @param HashMap $map 过滤条件
	 * @param string $sortBy 排序
	 * @param boolean $asc 是否正序
     +----------------------------------------------------------
	 * @return void
     +----------------------------------------------------------
	 * @throws ThinkExecption
     +----------------------------------------------------------
	 */
	protected function _list($model, $map, $sortBy = '') {
		//排序字段 默认为主键名
		$sort = '';
		if (isset ( $_REQUEST ['_order'] )) {
			$order = $_REQUEST ['_order'];
		} else {
			$fields = $model->getDbFields();
			$order = ! empty ( $sortBy ) ? $sortBy : (in_array('sort', $fields) ? 'sort desc,' : '').$model->getPk ();
		}
		//排序方式默认按照倒序排列
		//接受 sost参数 0 表示倒序 非0都 表示正序
		if (isset ( $_REQUEST ['_sort'] )) {
			$order .= $sort = $_REQUEST ['_sort'] ? ' asc' : ' desc';
		}elseif(empty ( $sortBy )) $order .= ' desc';
		//取得满足条件的记录数
		$count = $model->where ( $map )->count ( '*' );
		if ($count > 0) {
			import ( "ORG.Util.Page" );
			//创建分页对象
			if (! empty ( $_REQUEST ['listRows'] )) {
				$listRows = $_REQUEST ['listRows'];
			} else {
				$listRows = C('PAGE_LISTROWS');
			}
			//$listRows = 1; //测试
			$p = new Page ( $count, $listRows );
			//分页查询数据
			$voList = $model->where($map)->order($order)->limit($p->firstRow . ',' . $p->listRows)->select();
			//分页跳转的时候保证查询条件
			foreach ( $map as $key => $val ) {
				if (! is_array ( $val )) {
					$p->parameter .= "$key=" . urlencode ( $val ) . "&";
				}
			}			
			//分页显示
			$page = $p->show ();
			//列表排序显示
			$sortImg = $sort; //排序图标
			$sortAlt = $sort == 'desc' ? '升序排列' : '倒序排列'; //排序提示
			$sort = $sort == 'desc' ? 1 : 0; //排序方式
			$order = explode(' ',$order); $order = $order[0];
			//模板赋值显示
			$this->assign ( 'list', $voList );
			$this->assign ( 'sort', $sort );
			$this->assign ( 'order', $order );
			$this->assign ( 'sortImg', $sortImg );
			$this->assign ( 'sortType', $sortAlt );
			$this->assign ( "page", $page );
		}
		$this->assign ( 'totalCount', $count );
		$this->assign ( 'numPerPage', $listRows );
		$this->assign ( 'currentPage', is_numeric($_REQUEST[C('VAR_PAGE')])?$_REQUEST[C('VAR_PAGE')]:1);
		import ( "ORG.Util.Cookie" );	
		Cookie::set ( '_currentUrl_', __SELF__ );
		return;
	}

	function insert() {
		//B('FilterString');
		//值为数组的 转换成逗号分隔的字符串
		foreach($_POST as $key=>$val){
			if(is_array($val)){
				$_POST[$key] = implode(',', $val);
			}
		}
		$name=$this->getActionName();
		$model = D ($name);
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		$list=$model->add ();
		if ($list!==false) { //保存成功
			import ( "ORG.Util.Cookie" );
			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success ('新增成功!');
		} else {
			//失败提示
			$this->error ('新增失败!');
		}
	}

	public function add() {
		$this->display ();
	}

	function read() {
		$this->edit ();
	}

	function edit() {
		$name=$this->getActionName();
		$model = M ( $name );
		$id = $_REQUEST [$model->getPk ()];
		$vo = $model->find ( $id );
		$this->assign ( 'vo', $vo );
		$this->display ();
	}

	function update() {
		//B('FilterString');
		//值为数组的 转换成逗号分隔的字符串
		foreach($_POST as $key=>$val){
			if(is_array($val)){
				$_POST[$key] = implode(',', $val);
			}
		}		
		$name=$this->getActionName();
		$model = D ( $name );
		if (false === $model->create ()) {
			$this->error ( $model->getError () );
		}
		// 更新数据
		if ($model->save () !== false) {
			//成功提示
			import ( "ORG.Util.Cookie" );
			$this->assign ( 'jumpUrl', Cookie::get ( '_currentUrl_' ) );
			$this->success ('编辑成功!');
		} else {
			//错误提示
			$this->error ('编辑失败!');
		}
	}

	//删除到回收站
	public function delete() {
		$name=$this->getActionName();
		$model = M ($name);
		if (! empty ( $model )) {
			$pk = $model->getPk ();
			$id = $_REQUEST [$pk];
			if ( preg_match('/^\d+(,\d+)*$/',$id) ) {
				$condition = array ($pk => array ('in', $id ) );
				$list=$model->where ( $condition )->setField ( $name=='Category' ? 'classstatus' : 'status', - 1 );
				if ($list!==false) {
					$this->success ('删除成功！' );
				} else {
					$this->error ('删除失败！');
				}
			} else {
				$this->error ( '非法操作' );
			}
		}
	}
	
	//彻底删除
	public function foreverdelete() {
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			$pk = $model->getPk ();
			$id = $_REQUEST [$pk];
			if ( preg_match('/^\d+(,\d+)*$/',$id) ) {
				$condition = array ($pk => array ('in', $id ) );
				if (false !== $model->where ( $condition )->delete ()) {
					$this->success ('删除成功！');
				} else {
					$this->error ('删除失败！');
				}
			} else {
				$this->error ( '非法操作' );
			}
		}
		$this->forward ();
	}

	//清空回收站
	public function clear() {
		$name=$this->getActionName();
		$model = D ($name);
		if (! empty ( $model )) {
			if (false !== $model->where ( ($name=='Category' ? 'classstatus' : 'status').'=-1' )->delete ()) {
				$this->assign ( "jumpUrl", $this->getReturnUrl () );
				$this->success ( L ( '_DELETE_SUCCESS_' ) );
			} else {
				$this->error ( L ( '_DELETE_FAIL_' ) );
			}
		}
		$this->forward ();
	}
	
	//默认禁用操作
	public function forbid() {
		$name=$this->getActionName();
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_REQUEST [$pk];
		$condition = array ($pk => array ('in', $id ) );
		if ($model->forbid ( $condition, $name=='Category' ? 'classstatus' : 'status' )!==false) {
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->success ( '状态禁用成功' );
		} else {
			$this->error  (  '状态禁用失败！' );
		}
	}
	
	//批准状态
	public function checkPass() {
		$name=$this->getActionName();
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_REQUEST [$pk];
		$condition = array ($pk => array ('in', $id ) );
		if (false !== $model->checkPass( $condition, $name=='Category' ? 'classstatus' : 'status' )) {
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->success ( '状态批准成功！' );
		} else {
			$this->error  (  '状态批准失败！' );
		}
	}

	//从回收站还原
	public function recycle() {
		$name=$this->getActionName();
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_REQUEST [$pk];
		$condition = array ($pk => array ('in', $id ) );
		if (false !== $model->recycle ( $condition, $name=='Category' ? 'classstatus' : 'status' )) {
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->success ( '状态还原成功！' );

		} else {
			$this->error   ( '状态还原失败！' );
		}
	}
	
	//查看回收站
	public function recycleBin() {
		$name=$this->getActionName();
		$map = $this->_search ();
		$map [$name=='Category' ? 'classstatus' : 'status'] = - 1;
		$model = D ($name);
		if (! empty ( $model )) {
			$this->_list ( $model, $map );
		}
		$this->display ();
	}

	/**
     +----------------------------------------------------------
	 * 默认恢复操作
	 *
     +----------------------------------------------------------
	 * @access public
     +----------------------------------------------------------
	 * @return string
     +----------------------------------------------------------
	 * @throws FcsException
     +----------------------------------------------------------
	 */
	function resume() {
		//恢复指定记录
		$name=$this->getActionName();
		$model = D ($name);
		$pk = $model->getPk ();
		$id = $_REQUEST [$pk];
		$condition = array ($pk => array ('in', $id ) );
		if (false !== $model->resume ( $condition, $name=='Category' ? 'classstatus' : 'status' )) {
			$this->assign ( "jumpUrl", $this->getReturnUrl () );
			$this->success ( '状态恢复成功！' );
		} else {
			$this->error ( '状态恢复失败！' );
		}
	}

	/**
	 * 删除相应模型所有上传类字段，上传的文件 及其缩略相关文件 并返回记录ids
	 * @param $moduleName
	 * @return ids
	 */
	public function _beforDelFiles($module){
		$pk = M($module)->getPk();
		$pkValue = $_REQUEST[$pk];
		if( is_array($pkValue) || preg_match('/^\w+(,\w+)*$/',$pkValue) ){
			$pkValue = is_array($pkValue) ? $pkValue : explode(',',$pkValue);
			//-----------------------------------检测上传字段，取得上传字段的值，删除相应文件，同时要删除此文件的缩略图，复件等
			$needfields = array();
			$fields = M($module)->getDbFields();
			if(in_array('img', $fields)) $needfields[] = 'img';
			if(in_array('file', $fields)) $needfields[] = 'file';
			//取得其他上传字段
			$fieldsmap = M('model_fieldnotes')->where('ename="'.$module.'"')->getField('fieldsmap');
			if( $fieldsmap && is_array($fieldsmap = unserialize($fieldsmap)) ){
				foreach($fields as $val){
					//3:上传图片,4:上传文件
					if( in_array($fieldsmap[$val]['inputType'], array(3,4)) ) $needfields[] = $val;
				}
			}			
			if($needfields){ //有上传的字段则可以检测文件并删除
				$list = M($module)->where( array($pk=>array('in', $pkValue)) )->field($needfields)->select();
				if($list){
					import('ORG.Io.Dir');
					$rootpath = $_SERVER['DOCUMENT_ROOT'].__ROOT__.'/Public/Upload/'.strtolower($module).'/';
					$mfiles = Dir::getList($rootpath);
					$strmfiles = implode(':', $mfiles).':'; //为了性能把所有文件打包到字符串 :号不能命名在文件名里
					foreach($list as $rs){
						foreach($needfields as $field){
							if( preg_match('/^(https?|ftp):\/\//i', $rs[$field]) ) continue; //排除外部链接
							//取名称和后缀名
							$tmp = explode('.', $rs[$field]);
							$dbfileExt = $tmp[count($tmp)-1];
							unset($tmp[count($tmp)-1]);
							$dbfilename = implode('.', $tmp);
							//会删除相应的缩略图等文件
							if( preg_match_all('/[^:]*?'.preg_quote($dbfilename).'[^:]*?\.'.$dbfileExt.':/i', $strmfiles, $arrlikes) ){	
								foreach($arrlikes[0] as $perlike){
									//echo $perlike.'<br>';
									@unlink($rootpath.trim($perlike,':'));
								}
							}
						}
					}			
				}	
			}
			//-----------------------------------
			return $pkValue;
		}
		return 0;
	}
	
	//删除图片\视频\音乐等上传文件
	public function delfile(){
		$action = $this->getActionName();
		$pkname = M($action)->getPk();
		$field = ($_GET['field']!='') ? $_GET['field'] : 'img';
		if (method_exists ( $this, '_delfile' )) {
			$field = $this->_delfile();
		}
		if(is_numeric($_GET[$pkname])){
			$id = $_GET[$pkname];			
			$src = M($action)->where(array($pkname=>$id))->getField($field);
			M($action)->where(array($pkname=>$id))->setField($field,'');
			if( !preg_match('/^(https?|ftp):\/\//i', $src) ){//排除外部链接
				import('ORG.Io.Dir');
				$rootpath = $_SERVER['DOCUMENT_ROOT'].__ROOT__.'/Public/Upload/'.strtolower($action).'/';
				$mfiles = Dir::getList($rootpath);
				$strmfiles = implode(':', $mfiles).':'; //为了性能把所有文件打包到字符串 :号不能命名在文件名里
				//取名称和后缀名
				$tmp = explode('.', $src);
				$dbfileExt = $tmp[count($tmp)-1];
				unset($tmp[count($tmp)-1]);
				$dbfilename = implode('.', $tmp);
				//会删除相应的缩略图等文件
				if( preg_match_all('/[^:]*?'.preg_quote($dbfilename).'[^:]*?\.'.$dbfileExt.':/i', $strmfiles, $arrlikes) ){	
					foreach($arrlikes[0] as $perlike){
						//echo $perlike.'<br>';
						@unlink($rootpath.trim($perlike,':'));
					}
				}					
			}
		}
		echo 
		'<script type="text/javascript">
		var response = {
			"status":"1",
			"info":"\u64cd\u4f5c\u6210\u529f",
			"navTabId":"'.$action.'",
			"forwardUrl":"",
			"callbackType":"closeCurrent"
		};
		if(window.parent.donecallback) {
			 window.parent.donecallback(response);
		}
	   </script>';
	}	
	
    /**
     +----------------------------------------------------------
     * 默认排序操作
     +----------------------------------------------------------
     * @access public
     +----------------------------------------------------------
     * @return void
     +----------------------------------------------------------
     */
    public function setSort(){
    	$action = $this->getActionName();
		$pkname = M($action)->getPk();
		is_numeric($_GET[$pkname]) or $this->error($pkname.'参数错误');
		$field = ($_GET['field']!='') ? $_GET['field'] : ($action=='Category' ? 'classsort' : 'sort');
		M($action)->where(array($pkname=>$_GET[$pkname]))->save( array( $field=> is_numeric($_POST['value']) ? $_POST['value'] : 0 )  );		
		$this->success( M($action)->getError() ? M($action)->getError() : ucfirst($action) );
    }	
}